import { Typegoose, prop, staticMethod, ModelType } from 'typegoose';

export enum BaseModelDeleteStatus {
    normal = '0',
    delete = '1',
}

function genCond(cond: any) {
    if (!cond) cond = {};
    if (!('deleteStatus' in cond)) {
        cond.deleteStatus = BaseModelDeleteStatus.normal;
    }
    return cond;
}

function genAggregateCond(cond: any[]): any[] {
    if (!cond || !Array.isArray(cond)) {
        cond = [];
    }
    cond = [
        { $match: { deleteStatus: BaseModelDeleteStatus.normal } },
        ...cond,
    ];
    return cond;
}

export class BaseModel extends Typegoose {
    @prop({
        enum: BaseModelDeleteStatus,
        default: BaseModelDeleteStatus.normal,
    })
    deleteStatus: BaseModelDeleteStatus;

    @staticMethod
    static ybFind<T>(this: ModelType<T> & T, cond: any = {}) {
        return this.find(genCond(cond));
    }

    @staticMethod
    static ybFindOne<T>(this: ModelType<T> & T, cond: any = {}) {
        return this.findOne(genCond(cond));
    }

    @staticMethod
    static ybCount<T>(this: ModelType<T> & T, cond: any = {}) {
        return this.count(genCond(cond));
    }

    @staticMethod
    static ybAggregate<T>(this: ModelType<T> & T, cond: any[]) {
        return this.aggregate(genAggregateCond(cond));
    }
}
